<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene"></Category>
    <el-card style="margin: 10px 0;">
      <div v-show="scene == 0">
        <el-button type="primary" icon="Plus" :disabled="categoryStore.c3Id?false:true" @click="addAttr">添加属性</el-button>
        <el-table :data="attrArr" border style="margin: 10px 0;">
          <el-table-column type="index" label="序号" align="center" width="150px"/>
          <el-table-column label="属性名称" prop="attrName" width="200" align="center"/>
          <el-table-column label="属性值名称">
            <template #="{row}">
              <el-tag style="margin:0 5px;" v-for="(item,index) in row.attrValueList" :key="index">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #="{row}">
              <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
              <el-popconfirm :title="`你确定删除${row.attrName}吗？`" width="220px" @confirm="deleteAttr(row.id)">
                <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="Plus" :disabled="attrParams.attrName?false:true" @click="addAttrValue">添加属性值</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-table :data="attrParams.attrValueList" border style="margin: 10px 0;">
          <el-table-column width="150px" type="index" align="center" label="序号"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{row,$index}">
              <el-input :ref="(vc:any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row,$index)" v-model="row.valueName" placeholder="请输入属性值名称"></el-input>
              <div v-else @click="toEdit(row,$index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{row,index}">
              <el-button type="danger" size="small" icon="Delete" @click="attrParams.attrValueList.splice(index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length>0?false:true">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入组合式API函数watch
import { watch,ref,reactive,nextTick,onBeforeUnmount } from 'vue'
import {reqAttr,reqAddOrUpdate,reqRemoveAttr} from '@/api/product/attr/index'
import type {AttrResponseData,Attr,AttrValue} from '@/api/product/attr/type'
import useCategoryStore from '@/store/modules/category';
import { ElMessage } from 'element-plus';
let categoryStore = useCategoryStore()
let attrArr = ref<Attr[]>([]) //数组里面放Attr对象
// 卡片组件内容切换变量
let scene = ref<number>(0) //0:显示table 1:显示添加/修改
// 收集新增属性数据
let attrParams = reactive<Attr>({
  attrName: '', //属性名
  attrValueList: [], //属性值数组
  categoryId: '', //三级分类id
  categoryLevel: 3, //三级分类
})
// 准备数组存储对应的组件实例el-input
let inputArr = ref<any>([])
// 监听仓库三级分类id的变化
watch(()=>categoryStore.c3Id,()=>{
  // 三级id为空时，需要清空上次查询的数据
  attrArr.value = []
  //保证三级分类有id值才去获取数据
  if(!categoryStore.c3Id) return
  getAttr()
})
const getAttr = async()=> {
  // 从仓库中解构三个id对象（解构对象：确保categoryStore中有c1Id,c2Id,c3Id这三个属性）
  const {c1Id,c2Id,c3Id} = categoryStore
  let result:AttrResponseData = await reqAttr(c1Id,c2Id,c3Id)
  if(result.code == 200){
    attrArr.value = result.data
  }
}
const addAttr = ()=> {
  // 清空数据，Object.assign合并对象为初始状态
  Object.assign(attrParams,{
    attrName: '', //属性名
    attrValueList: [], //属性值数组
    categoryId: categoryStore.c3Id, //三级分类id
    categoryLevel: 3, //三级分类
  })
  scene.value = 1
  // // 获取三级分类id
  // attrParams.categoryId = categoryStore.c3Id
}
const updateAttr = (row:Attr)=> {
  scene.value = 1
  // 修改数据回显
  console.log(row);
  // ES6->Object.assifn进行对象合并，
  // 对象中嵌套数组，Object.assign(attrParams,row)浅拷贝，指向的是同一个内存地址，
  // JSON.parse(JSON.stringify(row))深拷贝修改数据不影响原数组
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}
const cancel = ()=> {
  scene.value = 0
}
const addAttrValue = ()=> {
  attrParams.attrValueList.push({
    valueName:'',
    flag:true, //控制每一个属性值编辑与查看的切换
  })
  // 点击添加按钮，响应式数据发生变化，模板需要一定时间渲染，不能立刻获取到dom，
  // 使用nextTick获取响应式数据更新后的dom再执行操作
  // 获取最后的el-input组件并聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length-1].focus()
  })
}
const save = async() => {
  let result:any = await reqAddOrUpdate(attrParams)
  if(result.code == 200){
    scene.value = 0
    ElMessage.success(attrParams.id?'修改成功！':'添加成功！')
    getAttr()
  }else{
    ElMessage.error(attrParams.id?'修改失败！':'添加失败！')
  }
}
const toLook = (row:AttrValue,$index:number)=> {
  // 用户未输入时，不显示div
  if(row.valueName.trim() == ''){
    // 删除属性值为空的那行数据
    attrParams.attrValueList.splice($index,1)
    ElMessage.error('属性值不能为空')
    return
  }
  // 新增的属性值名称唯一
  let repeat = attrParams.attrValueList.find(item => {
    // 把当前失去焦点的属性值对象从当前数组中剔除 再判断
    if(item!=row){
      return item.valueName == row.valueName
    }
  })
  if(repeat){
    // 删除属性值重复的那行数据
    attrParams.attrValueList.splice($index,1)
    ElMessage.error('属性值不能重复')
    return
  }
  row.flag = false
}
const toEdit = (row:AttrValue,$index:number)=> {
  row.flag = true
  // nextTick:响应式数据发生变化，获取响应式数据更新后的dom（组件实例）
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
const deleteAttr = async(attrId:number)=> {
  let result = await reqRemoveAttr(attrId)
  if(result.code == 200){
    ElMessage.success('删除成功！')
    getAttr()
  }else{
    ElMessage.error('删除失败！')
  }
}
// 路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(()=> {
  // 清空仓库数据
  categoryStore.$reset()
})
</script>

<style scoped lang="scss">

</style>